//
//  MYGMessageIndexController.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/2/29.
//

import UIKit

class MYGMessageIndexController: MYGBaseController {
    // MARK: - Property
    var contents: [MYGChatListSection] = []
    
    var headers: [MYGChatListSection] = []
    
    private var strangeMessageList: [MYGIMMessageListSessionModel] = []
    // MARK: - life cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
        configItem()
        
        NotificationCenter.default.addObserver(self, selector: #selector(configItem), name: NSNotification.Name.init("MYGIMMessageList"), object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
//        configItem()
    }
    
    // MARK: - 配置Cell
    @objc
    private func configItem() {
        contents = []
        self.strangeMessageList = []
//        guard let model = MYGSocketManager.shared.totalMessage else {
//            return
//        }
        
        let model = MYGSocketManager.shared.totalMessage
        
        let system = model?.session.filter { item in
            item.sessionInfo.type == .service
        }
        
        var text = "暂无系统消息"
        var time = ""
        if let system = system?.first {
            text = system.lastMessage.last_message
        }
        
        let systemItem = MYGChatListCellModel(image: "system", name: "系统消息", content: text, time: time, isNetwork: false, id:0)
        
//        let strange = model?.session.filter { item in
//            item.sessionInfo.type == .single && !item.sessionInfo.pushUser.friend
//        }
        

        if let session = model?.session, !session.isEmpty {
            self.strangeMessageList += session.filter { $0.mo_shenggx == 1 }.map { $0 }
        }
        
        text = "暂无陌生消息"
        time = ""
//        if let first = strange?.first {
//            if first.lastMessage.is_destruction == 1 {
//                text = "阅后即焚"
//            } else {
//                text = first.lastMessage.last_message
//            }
//            time = first.lastMessage.last_time
//        }
     
        if strangeMessageList.count > 0 {
           if let first = strangeMessageList.first {
               text = first.lastMessage.last_message
               time = first.lastMessage.last_time
            }
        }
        
        let strangeItem = MYGChatListCellModel(image: "strange", name: "陌生消息", content: text, time: time, isNetwork: false, showLine: false,id: 0)
        let systemSection = MYGChatListSection(items: [systemItem, strangeItem], footerHeight: 4)
//        let systemSection = MYGChatListSection(items: [systemItem], footerHeight: 4)
        
        headers.append(systemSection)
        
        headerView.model = systemItem
        moheaderView.model = strangeItem
        
        let friends = model?.session.filter { item in
            //item.sessionInfo.type == .single && item.sessionInfo.pushUser.friend
            item.sessionInfo.type == .single && item.mo_shenggx == 0
        }
        var chatSection = MYGChatListSection(items: [])
        for item in friends ?? [] {
            var model = MYGChatListCellModel(image: item.sessionInfo.pushUser.avatar, name: item.sessionInfo.pushUser.nickname, content: item.lastMessage.last_message, time: item.lastMessage.last_time,id: 1,unreadMessagesNumber: item.unreadMessagesNumber)
            if item.lastMessage.is_destruction == 1 {
                model.content = "阅后即焚"
            }
            model.clickAction = {[weak self] in
                let vc = MYGChatController(sessionId: item.sessionInfo.id,title: item.sessionInfo.pushUser.nickname)
                vc.unreadMessagesNumber = item.unreadMessagesNumber
                self?.navigationController?.pushViewController(vc)
            }
            chatSection.items.append(model)
        }
        
        contents.append(chatSection)
        tableView.reloadData()
    }
    
    // MARK: - UI
    private func configUI() {
        self.title = "消息"
        let rightBar = UIBarButtonItem(image: UIImage.init(named: "icon_tianjia"), style: .plain, target: self, action: #selector(clickAddBtn))
        rightBar.tintColor = .black
        self.navigationItem.rightBarButtonItem = rightBar

        
        view.addSubview(tableView)
        view.addSubview(headerView)
        view.addSubview(moheaderView)
        headerView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(70)
        }
        moheaderView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(70)
        }
        
        tableView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(moheaderView.snp.bottom)
        }
    }
    
    // MARK: - lazy load
    private lazy var tableView: UITableView = {
        let tableV = UITableView()
        tableV.separatorStyle = .none
        tableV.delegate = self
        tableV.dataSource = self
        tableV.backgroundColor = .white
        tableV.register(cellWithClass: MYGChatListCell.self)
        return tableV
    }()
    
    private lazy var headerView:MYGChatTopView = {
        let v = MYGChatTopView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 70))
        
        let gesture = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        v.addGestureRecognizer(gesture)
        
        return v
    }()
    
    private lazy var moheaderView:MYGChatTopView = {
        let v = MYGChatTopView(frame: CGRect(x: 0, y: 70, width: screenWidth, height: 70))
        
        let gesture = UITapGestureRecognizer(target: self, action: #selector(tapStrangeAction))
        v.addGestureRecognizer(gesture)
        
        return v
    }()
    
    @objc func tapAction(){
        let vc = MYGSystemMessageController()
        self.navigationController?.pushViewController(vc)
    }
    
       @objc func clickAddBtn(){
            let vc = MYGAddFriendViewController()
            self.navigationController?.pushViewController(vc)
    }

    @objc func tapStrangeAction(){
        let vc = MYGStrangMessageViewController()
        vc.strangeMessageList = strangeMessageList
        self.navigationController?.pushViewController(vc)
    }
}

extension MYGMessageIndexController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        contents.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        contents[section].items.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        70
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: MYGChatListCell.self, for: indexPath)
        cell.model = contents[indexPath.section].items[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = .rgba(250, 250, 250, 1)
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return contents[section].footerHeight
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        contents[indexPath.section].items[indexPath.row].clickAction?()
    }
}
